<template>
  <div class="box">
    <div class="top">
      <h1 class="title01">温度管理</h1>
      <div class="operation">
        <el-select
          v-model="searchClass"
          clearable
          placeholder="请选择搜索类型"
          style="width: 120px"
          @change="searchValue = ``"
        >
          <el-option
            v-for="item in options"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
        <el-select
          v-if="searchClass === 'delstate'"
          v-model="searchValue"
          clearable
          placeholder="请选择搜索类型"
          style="width: 120px; margin: 0 10px 0 10px"
        >
          <div>
            <el-option
              v-for="item in optionsInformationState"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </div>
        </el-select>
        <el-input
          v-else
          v-model="searchValue"
          placeholder="请输入搜索内容"
          clearable
          class="input"
          type="number"
          style="width: 120px; margin: 0 10px 0 10px"
        />
        <el-button type="primary" @click="handleSearch" :loading="loading"
          >查询</el-button
        >
        <el-button
          type="primary"
          @click="OpenDialog('', 'add')"
          :disabled="equipmentInexistence"
          >新增</el-button
        >
      </div>
    </div>
    <!-- 内容 -->
    <div class="main">
      <!-- 表格渲染内容 -->
      <div class="table">
        <el-table :data="tableData" style="width: 100%" empty-text="暂无数据">
          <el-table-column fixed label="序号" width="80">
            <template #default="{ $index }">
              {{ startIndex + $index }}
            </template>
          </el-table-column>
          <!-- <el-table-column prop="plantname" label="植物名" /> -->
          <!-- <el-table-column prop="did" label="设备id" /> -->
          <el-table-column prop="nowtemp" label="当前温度">
            <template #default="scope">
              <div v-if="!scope.row.nowtemp">---</div>
              <div
                v-else
                :class="
                  scope.row.tempmax < scope.row.nowtemp ||
                  scope.row.tempmin > scope.row.nowtemp
                    ? 'color-red'
                    : ''
                "
              >
                {{ scope.row.nowtemp + "°C" }}
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="tempmax" label="温度上限">
            <template #default="scope">
              <div
                :class="
                  scope.row.tempmax < scope.row.nowtemp ? 'color-red' : ''
                "
              >
                {{ scope.row.tempmax + "°C" }}
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="tempmin" label="温度下限">
            <template #default="scope">
              <div
                :class="
                  scope.row.tempmin > scope.row.nowtemp &&
                  scope.row.nowtemp !== null
                    ? 'color-red'
                    : ''
                "
              >
                {{ scope.row.tempmin + "°C" }}
              </div>
            </template>
          </el-table-column>
          <!-- <el-table-column prop="createby" label="创建人"/> -->
          <el-table-column
            prop="remark"
            label="删除原因"
            width="380"
            align="center"
          >
            <template #default="scope">
              <div v-if="scope.row.remark">
                {{ scope.row.remark }}
              </div>
              <div v-else-if="scope.row.delstate === 1">
                {{ "已删除, 但用户未写删除原因" }}
              </div>
            </template>
          </el-table-column>
          <el-table-column fixed="right" label="操作" min-width="80">
            <template #default="scope">
              <!-- <el-button
                link
                type="primary"
                size="small"
                :disabled="scope.row.delstate === 1"
                @click="OpenDialog(scope.row, 'edit')"
                >修改</el-button
              > -->
              <el-button
                link
                type="primary"
                size="small"
                :disabled="scope.row.delstate === 1"
                @click="DeleteForm(scope.row)"
                >删除</el-button
              >
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>
    <!-- 模态窗新增/修改列表 -->
    <el-dialog v-model="dialogVisible" width="550" :before-close="handleClose">
      <h1 class="title01">
        {{ dialogTitle ? "修改温度信息" : "新增温度信息" }}
      </h1>
      <el-form
        ref="ruleFormRef"
        :model="NewForm"
        :rules="FormRules"
        class="form"
      >
        <!-- 温度设置 -->
        <div>
          <el-form-item
            label="温度上限"
            prop="tempmax"
            label-width="80px"
            label-position="left"
            class="justify-label"
          >
            <el-input
              v-model="NewForm.tempmax"
              type="number"
              placeholder="请输入温度上限"
              controls-position="right"
            >
              <template #append>℃</template>
            </el-input>
          </el-form-item>
          <el-form-item
            label="温度下限"
            prop="tempmin"
            label-width="80px"
            label-position="left"
            class="justify-label"
          >
            <el-input
              v-model="NewForm.tempmin"
              type="number"
              placeholder="请输入温度下限"
            >
              <template #append>℃</template>
            </el-input>
          </el-form-item>
        </div>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="handleClose">取消</el-button>
          <el-button type="primary" :loading="loading" @click="ConfirmAddition">
            提交
          </el-button>
        </div>
      </template>
    </el-dialog>
    <!-- 删除的弹窗 -->
    <el-dialog
      v-model="deleteDialogVisible"
      title="你确认要删除吗？"
      width="500"
      :before-close="handleClose"
    >
      <div style="display: flex; margin: 5px 0 0 0">
        <div style="margin: 0px 15px 10px 0">请输入删除原因</div>
        <div v-if="remarkExceedsLimit" class="error-message">
          字数超出限制！
        </div>
        <div v-else>
          {{ `${NewForm.remark.length}/25` }}
        </div>
      </div>
      <div style="width: 350px">
        <el-input
          v-model="NewForm.remark"
          maxlength="25"
          :class="{ 'error-input': remarkExceedsLimit }"
        />
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="deleteDialogVisible = false">取消</el-button>
          <el-button
            type="primary"
            :loading="deleteLoading"
            @click="confirmDeletion"
          >
            确认
          </el-button>
        </div>
      </template>
    </el-dialog>
    <!-- 分页 -->
    <div class="example-pagination-block">
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="pageInfo.currentPage"
        :page-size="pageInfo.pageSize"
        :total="pageInfo.total"
        layout="prev, pager, next"
      />
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted, onUnmounted } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import {
  getTemperatureList,
  queryTemperatureList,
  // deleteTemperatureList,
  addTemperatureList,
  updaTetemperatureList,
  queryTemperatureEquipment,
  // queryPlantNameAndId,
} from "@/api/temperature";

// 新增加载状态标志
const loading = ref(false);
const deleteLoading = ref(false);

// 页码信息
const pageInfo = reactive({
  pageNum: 1,
  pageSize: 10,
});

// 表格序号起始值
const startIndex = computed(() => {
  return (pageInfo.pageNum - 1) * pageInfo.pageSize + 1;
});

// 限制文本域输入字数
const remarkExceedsLimit = computed(() => {
  return NewForm.remark.length >= 25;
});

// 表格数据，渲染表格
const tableData = ref([]);

//用于判断设备是否存在
const equipmentInexistence = ref(true);
//暂存设备id
const did = ref("");
// 搜索框内容
const searchValue = ref("");
// 搜索类型
const searchClass = ref("");

// 模态窗状态
const dialogVisible = ref(false);
// 删除模态窗状态
const deleteDialogVisible = ref(false);
// 用于确认模态窗标题状态和新增修改状态
const dialogTitle = ref(false);

// 表单验证
const ruleFormRef = ref(null);

// 设备列表
const equipmentList = reactive([]);

const options = [
  { value: "tempmax", label: "温度上限" },
  { value: "tempmin", label: "温度下限" },
  { value: "delstate", label: "删除状态" },
];
const optionsInformationState = [
  {
    value: "0",
    label: "正常的",
  },
  {
    value: "1 ",
    label: "已删除的",
  },
];
// 新增/修改表单
const NewForm = reactive({
  // 温度ID
  tid: "",
  // 当前温度
  nowtemp: "",
  // 设备ID
  did: "",
  // 温度上限
  tempmax: "",
  // 温度下限
  tempmin: "",
  // 创建时间
  createtime: "",
  // 创建人
  createby: "",
  // 备注
  remark: "",
  //删除状态//  0：未删除  1：已删除
  delstate: "0",
});
// 表单验证规则
const validateTemperatureRange = (rule, value, callback) => {
  if (NewForm.tempmax && NewForm.tempmin) {
    const max = parseFloat(NewForm.tempmax);
    const min = parseFloat(NewForm.tempmin);
    if (max < 0 || max > 60 || min < 0 || min > 60) {
      callback(new Error("温度必须在0到60之间"));
    } else if (max < min) {
      callback(new Error("温度上限不可低于温度下限"));
    } else {
      callback();
    }
  } else {
    callback();
  }
};

// 表单验证规则
const FormRules = {
  // did: [{ required: true, message: "请输入设备ID", trigger: "blur" }],
  tempmax: [
    { required: true, message: "请输入温度上限", trigger: "blur" },
    { validator: validateTemperatureRange, trigger: "blur" },
  ],
  tempmin: [
    { required: true, message: "请输入温度下限", trigger: "blur" },
    { validator: validateTemperatureRange, trigger: "blur" },
  ],
  remark: [{ max: 25, message: "备注最多25个字符", trigger: "blur" }],
};

// 获取设备状态，确认用户是否拥有设备，
const getTemperatureEquipment = async () => {
  let res = await queryTemperatureEquipment();
  if (res.code === 200) {
    if (res.data !== null) {
      // 设备存在
      equipmentInexistence.value = false;
      did.value = res.data[0].did;
    } else {
      // 设备不存在
      equipmentInexistence.value = true;
      ElMessage.error("您当前没有设备");
    }
  } else {
    ElMessage.error("获取设备信息失败，请重试");
  }
};
// //获取植物名称和id
// const getPlantNameAndId = async () => {
//   let res = await queryPlantNameAndId();
//   if (res.code === 200) {
//     console.log(res.data);
//   } else {
//     ElMessage.error("获取植物信息失败，请重试");
//   }
// };

// 获取表格数据，请求数据，渲染表格
const gettableData = async () => {
  loading.value = true;
  try {
    let res = await getTemperatureList({
      pageNum: pageInfo.pageNum,
      pageSize: pageInfo.pageSize,
    });
    if (res.code === 200) {
      tableData.value = res.data.records;
      pageInfo.total = res.data.total;
    }
  } catch (error) {
    ElMessage.error("获取数据失败，请重试");
    console.error(error);
  } finally {
    loading.value = false;
  }
};

// 页码变化时触发
const handleCurrentChange = (val) => {
  pageInfo.pageNum = val;
  gettableData();
};

// 页面展示数据变化时触发
const handleSizeChange = (val) => {
  pageInfo.pageSize = val;
  gettableData();
};

// 打开模态窗，通过判断type判断是新增还是修改，渲染表单
const OpenDialog = async (row, type) => {
  dialogVisible.value = true;
  if (type === "edit" && row) {
    dialogTitle.value = true;
    Object.assign(NewForm, row);
  } else if (type === "add") {
    dialogTitle.value = false;
    resetNewForm();
    NewForm.did = did.value;
  }
};

// 确认按钮触发，验证表单，提交数据，关闭模态窗，刷新表格
const ConfirmAddition = async () => {
  // 设置加载状态
  loading.value = true;
  ruleFormRef.value.validate(async (valid) => {
    if (valid) {
      try {
        const res = dialogTitle.value
          ? await updaTetemperatureList(NewForm)
          : await addTemperatureList(NewForm);

        if (res.code === 200) {
          ElMessage.success(res.msg);
          gettableData();
          handleClose();
        }
      } catch (error) {
        ElMessage.error("操作失败，请重试");
        console.error(error);
      } finally {
        // 无论成功还是失败，都关闭加载状态
        loading.value = false;
      }
    } else {
      ElMessage.error("请输入完整的有效信息");
      // 无论成功还是失败，都关闭加载状态
      loading.value = false;
    }
  });
};

const handleClose = () => {
  dialogVisible.value = false;
  deleteDialogVisible.value = false;
  resetNewForm();
};

// 搜索按钮触发，请求数据，渲染表格
const handleSearch = async () => {
  loading.value = true;
  try {
    if (!searchValue.value) {
      gettableData();
      return;
    }
    let res = await queryTemperatureList({
      searchClass: searchClass.value,
      searchValue: searchValue.value,
      pageNum: pageInfo.pageNum,
      pageSize: pageInfo.pageSize,
    });
    if (res.code === 200) {
      tableData.value = res.data.records;
      pageInfo.total = res.data.total;
      ElMessage.success(res.msg);
    } else {
      ElMessage.error(res.msg);
    }
  } catch (error) {
    ElMessage.error("搜索操作失败，请重试");
    console.error(error);
  } finally {
    loading.value = false;
  }
};

// 删除弹窗触发，确认删除时发送该列数据的删除状态，和删除原因
const confirmDeletion = async () => {
  deleteLoading.value = true; // 设置加载状态
  try {
    NewForm.delstate = 1;
    const res = await updaTetemperatureList(NewForm);
    if (res.code === 200) {
      ElMessage.success("标记删除成功");
      gettableData();
      handleClose();
    }
  } catch (error) {
    ElMessage.error("操作失败，请重试");
    console.error(error);
  } finally {
    deleteLoading.value = false; // 无论成功还是失败，都关闭加载状态
  }
};

// 删除按钮触发，弹出确认框，确认后标记删除
const DeleteForm = (row) => {
  deleteDialogVisible.value = true;
  Object.assign(NewForm, row);
};

// 重置新增/修改表单内容
const resetNewForm = () => {
  if (ruleFormRef.value) ruleFormRef.value.resetFields();
};

// 页面加载时触发，请求数据，渲染表格
//定义定时器
let intervalId = null;
onMounted(() => {
  gettableData();
  getTemperatureEquipment();
  // getPlantNameAndId();
  // 每隔5分钟重新请求刷新数据
  intervalId = setInterval(() => {
    gettableData();
    getLightEquipment();
  }, 300000);
});
//页面销毁时清除定时器;
onUnmounted(() => {
  clearInterval(intervalId);
});
</script>

<style lang="scss" scoped>
.box {
  .top {
    display: flex;
    justify-content: space-between;
    .operation {
      display: flex;
      align-items: center;
    }
  }
  .main {
    .table {
      width: 100%;
      .hasRemark {
        text-decoration: underline;
      }
    }
  }
  .el-dialog {
    h1 {
      margin-bottom: 20px;
    }
    .form {
      .el-input {
        width: 28vh;
        margin: 0 10px 5px 0;
      }
      .error-message {
        color: red;
      }
    }
  }
  .noRemark {
    color: #999;
  }
  .el-pagination {
    margin: 0;
    padding: 0;
    position: absolute;
    bottom: 21px;
  }
  .dialog-title {
    font-size: 18px;
    margin: 0 0 30px 0;
  }
  .highlight {
    background-color: #09a745;
  }
}
.color-red {
  color: red;
}
</style>
